# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  # Pick a unique cookie name to distinguish our session data from others'
  session :session_key => '_trinit_session_id'
  before_filter :find_this_blog
  
  
  def sql_paginator(collections_id, options={})
    default_options = {:per_page => 10}
    options = default_options.merge options
    
    models_pages, models = paginate collections_id, options
    first_pager, last_pager, has_pre_pager, has_next_pager = cal_paginate_bar(models_pages.current.number, models_pages.first.number, models_pages.last.number)
    return [models_pages, models, first_pager, last_pager, has_pre_pager, has_next_pager]
  end
  
  private
  
  def cal_paginate_bar(current_page_num = 1,first_page_num =0,last_page_num = 0)
    left_offset = current_page_num % 5
    left_offset = 5 if left_offset == 0
    first_pager = current_page_num - left_offset + 1
    
    has_pre = false
    has_next = false
    
    if first_pager > first_page_num
      has_pre = true
    else
      first_pager = first_page_num
    end
    
    last_pager = first_pager + 4
    
    if last_pager < last_page_num
      has_next = true
    else
      last_pager = last_page_num
    end
    
    return [first_pager, last_pager, has_pre, has_next]
  end
  
  def find_this_blog
    if params == nil || params[:username] == nil
      go_to_404
    else
      user = User.find(:first, :conditions => "unique_name = '#{params[:username]}'")
      if user == nil
        go_to_404
      else
        @this_blog = user.blog
      end
    end
  end
  
  def authorize
    unless User.find_by_id(session[:user_id])
      session[:origin_uri] = request.request_uri
      flash[:notice] = 'Please sign in.'
      redirect_to :controller => '/sign', :action => 'in'
    end
  end
  
  def set_signed_user
    @signed_user = User.find_by_id(session[:user_id])
    if @signed_user.nil?
      session[:origin_uri] = request.request_uri
    end
  end
  
  def go_to_404
    render :file => "#{RAILS_ROOT}/public/404.html", :status => 404 and return
  end
end
